package webmarket.common;

import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public abstract class XmlBase implements Serializable {
	private static final long serialVersionUID = 7870057380511412728L;

	protected void addAttitionalClasses(List<Class<? extends XmlBase>> classList) {

	}

	@Override
	public String toString() {
		String result = "";
		List<Class<? extends XmlBase>> classes = new ArrayList<Class<? extends XmlBase>>();
		classes.add(this.getClass());
		addAttitionalClasses(classes);
		try {
			//String packageName = this.getClass().getPackage().getName();
			Class[] classArray = new Class[classes.size()];
			classes.toArray(classArray);
			
			JAXBContext jc = JAXBContext.newInstance(classArray);
			Marshaller m = jc.createMarshaller();
			m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			m.marshal(this, outStream);
			result = new String(outStream.toByteArray());
		} catch (JAXBException e) {
			result = "Exception during serializing class: " + this.getClass() + "\r\n" + e.getMessage() + ":"
					+ Arrays.toString(e.getStackTrace()).replace(",", ",\n");
		}
		return result;
	}
}
